/**
 * @name					Enhanced Forms
 * @descripton				Enhanced Forms is a jQuery plugin that improves the default support for handling and manipulating forms.
 * @version					1.8.0
 * @requires				jQuery 1.8.0+
 *
 * @author					Sam Vervaeck
 * @author-email			sam@vervaeck.be
 * @author-website			http://sam.vervaeck.be
 *
 * @licence					GNU General Public License - http://www.gnu.org/licenses/gpl-3.0.html
 */

(function($){ 
	$.fn.extend({
	
		// Makes it possible to collapse fieldsets
		collapsable: function () {
			
			this.each(function () {
			
				if (this.tagName == 'FIELDSET') {
				
					var fieldset = $(this);
					
					// Make the fieldsets collapsable
					fieldset.children("legend").click(function () {
						$(this).nextAll().toggle();
					});
					
					// Collapse marked fieldsets
					if (fieldset.hasClass("collapsed")) {
						fieldset
							.removeClass("collapsed")
							.children("legend").nextAll().hide();
					}
					
				// Search for other fieldsets
				} else {
					$(this).children().collapsable();
				}
			});
			
			// Continue jQuery
			return this;
		},
		
		// Convenient method to lookup one or more form fields
		fields: function (name) {
			
			// TODO: support infinite arguments
			var names = arguments;
			
			// This function only works on forms
			if (! this.is("form")) {
				return false;
			}
				
			var fields =  $(this).find("input, textarea, select");
				
			// Unify ID and NAME attribute (both are valid)
			return name ? fields.filter("[type!=radio][id=" + name + "],[type=radio][name=" + name + "]") : fields;
		},
		
		// Make subfields for a certain field dynamic
		subform: function(predicate) {
			
			// By default the main field will be a checkbox or radio button
			if (predicate === undefined) {
				predicate = "input:checked";
			}
			
			var fields = this;
			
			// Function to show subform for certain field
			function update () {
				fields.first().nextAll().not(fields).hide();
				fields.filter(function () {
					return $(this).find(predicate).length;
				}).each(function () {
					$(this).nextUntil(fields).show();
				});
			}
			
			// Bind event to the 
			fields.change(update);
			update ();
			
			// Continue jQuery
			return this;
        }
    });
})(jQuery);